<!--  修改用户的页面-->
<template>
  <div>
    <el-form ref="formData" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="用户账号" prop="userId">
        <el-input v-model="formData.userId"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="formData.gender">
          <el-radio label="男">男</el-radio>
          <el-radio label="女">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="系部" prop="department">
        <el-input v-model="formData.department"></el-input>
      </el-form-item>
      <el-form-item label="班级" prop="clbum">
        <el-input v-model="formData.clbum"></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="contactInfo">
        <el-input v-model="formData.contactInfo"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="formData.role" placeholder="请选择">
          <el-option label="宿管" value="0"></el-option>
          <el-option label="学生" value="1"></el-option>
          <el-option label="管理员" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-if="false" label="是否锁定" prop="isLocked">
        <el-switch v-model="formData.isLocked" active-value="true" inactive-value="false"></el-switch>
      </el-form-item>
      <el-form-item v-if="false" label="创建时间" prop="createdAt">
        <el-date-picker
            v-model="formData.createdAt"
            placeholder="选择日期时间"
            type="datetime">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">保 存</el-button>
        <el-button type="info" @click="cancellation">取 消</el-button>
        <el-button type="danger" @click="resetPassword">重置密码</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: 'Default Message' // 设置 message 的默认值为 'Default Message'
    },
  },
  data() {
    return {
      formData: {
        userId: '',
        name: '',
        gender: '',
        department: '',
        clbum: '',
        contactInfo: '',
        email: '',
        role: '',
        avatarUrl: ''
      },
      rules: {
        userId: [
          {required: true, message: '请输入用户账号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        gender: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        role: [
          {required: true, message: '请选择角色', trigger: 'change'}
        ]
        // 添加其他字段的验证规则
      }
    };
  },
  watch: {
    // 监听 message 属性的变化
    message(newValue, oldValue) {
      this.getUsersById(newValue);
    },
  },
  mounted() {
    // 组件挂载后立即获取数据
    this.getUsersById(this.message);
  },
  methods: {
    // 根据ID查询按钮
    getUsersById(userId) {
      this.clearAway();
      // 发送 POST 请求获取单元列表
      this.$axios.get('/api/users/' + userId, {
        headers: {
          'token': this.$store.getters.getToken
        }
      })
          .then(response => {
            // 请求成功，从响应中提取出需要的数据
            const data = response.data;
            if (data.code === 200) {
              this.formData = response.data.data;
            } else {
              this.$message.error(response.data.msg || '获取用户信息失败');
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    updateUser() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.$axios.put('/api/users/update', this.formData, {
            headers: {
              'token': this.$store.getters.getToken
            }
          })
              .then(response => {
                this.clearAway();
                if (response.data.code === 200) {
                  this.$emit('UpdateUsers');
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                } else {
                  this.$message.error(response.data.msg || '修改用户失败');
                }
              })
              .catch(error => {
                this.clearAway();
                // 自定义一个事件，使其能够添加成功之后自动隐藏！
                this.$emit('UpdateUsers');
                // 处理错误情况
                this.$message({
                  message: '添加失败',
                  type: 'error'
                });
              });
          this.$emit('UpdateUsers');
          // 表单验证通过，执行添加用户逻辑
          console.log('用户信息已提交：', this.formData);
        } else {
          // 表单验证失败，不执行添加用户逻辑
          return false;
        }
      });
    },
    // 重置密码
    resetPassword() {
      this.$axios.put('/api/users/update/' + this.formData.userId, {
        headers: {
          'token': this.$store.getters.getToken
        }
      })
          .then(response => {
            // 请求成功，从响应中提取出需要的数据
            const data = response.data;
            if (data.code === 200) {
              this.$message({
                message: '重置密码成功',
                type: 'success'
              });
            } else {
              this.$message.error(response.data.msg || '重置密码失败');
            }
          })
          .catch(error => {
            console.error('Error fetching users:', error);
          });
    },
    clearAway() {
      this.formData.userId = '';
      this.formData.name = '';
      this.formData.gender = '';
      this.formData.department = '';
      this.formData.class = '';
      this.formData.contactInfo = '';
      this.formData.email = '';
      this.formData.role = '';
      this.formData.avatarUrl = '';
    },
    cancellation() {
      this.$emit('UpdateUsers');
    }
  }
};
</script>

<style>

</style>
